package cn.example.demo.modules.sys.init;

import cn.example.demo.common.dictionary.SystemConstant;
import cn.example.demo.common.model.service.ServiceResult;
import cn.example.demo.modules.sys.dict.DictNameConstant;
import cn.example.demo.modules.sys.model.entity.SysUser;
import cn.example.demo.modules.sys.service.DeptService;
import cn.example.demo.modules.sys.service.UserServiceImpl;
import cn.hutool.core.util.StrUtil;
import com.github.benmanes.caffeine.cache.Cache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.http.HttpStatus;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * <p>
 * 系统管理信息初始化
 * </p>
 *
 * @author Lizuxian
 * @create 2022/3/13 15:44
 */
@Slf4j
@Component
public class Initializer implements ApplicationRunner {
    private final PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Value("${global.admin.init-pass}")
    private String adminInitPass;  // 超级管理员账号初始化密码

    @Value("${global.admin.overwrite}")
    private boolean isOverWrite = false;  // 是否覆盖

    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private Cache<String, Object> dictCache;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 1.初始化管理员账号信息
        initSuperAdminPassword();
        // 2.初始化字典信息
        initDict();
    }

    /**
     * 初始化超级管理员账号密码
     */
    private void initSuperAdminPassword() {
        SysUser sysUser = userService.getById(1);
        if (sysUser != null && isOverWrite) {
            sysUser.setPassword(StrUtil.isNotBlank(adminInitPass) ? passwordEncoder.encode(adminInitPass) : passwordEncoder.encode("123456"));
            if (userService.updateById(sysUser)) {
                log.info(SystemConstant.rootUserName + " 账号密码已初始化！");
            }
        }
    }

    /**
     * 初始化字典信息
     */
    private void initDict() {
        // 初始化数据权限：组织树
        ServiceResult result = deptService.queryOrgTreeWithFlatChild(true);
        if (HttpStatus.OK.value() == result.getStatus()) {
            // 将组织机构树添加到缓存
            dictCache.put(DictNameConstant.ORGANIZATION_TREE_LIST, result.getData());
        }
    }
}
